import concurrent.futures
import logging
import random
import time
from concurrent.futures import as_completed
from datetime import datetime

from tqdm import tqdm

from tools import time_tool


def test_worker(data_name):
    try:
        start_time = datetime.now()
        """模拟随机I/O延迟"""
        delay = random.uniform(0.1, 2.0)
        time.sleep(delay)
        end_time = datetime.now()
        time_diff = end_time - start_time
        return f"{data_name} 成功,耗时 {time_tool.format_timedelta(time_diff)}"
    except Exception as e:
        return f"{data_name} 失败: {e}"


def worker_pool_one_submit():
    """
    demo演示,线程池执行io任务，线程池只提交一次批量任务
    """
    start_time = datetime.now()
    workers = 3
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
        # 任务数量
        # min(10,count)
        tasks = []
        futures = []
        for VideoFile_record in tasks:
            futures.append(executor.submit(test_worker, VideoFile_record.name))
        # 按完成的顺序遍历, 不按照futures提交的顺序遍历
        for future in tqdm(as_completed(futures), total=len(futures), desc="thread_pool_one_submit 任务",
                           colour="green", dynamic_ncols=True,
                           bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} ({elapsed} 剩余时间 {remaining})\n", ):
            future.result()  # 实际每次阻塞发生的位置
    end_time = datetime.now()
    time_diff = end_time - start_time
    logging.info(f"完成{len(tasks)}个任务,耗时 {time_tool.format_timedelta(time_diff)}")

# def worker_pool():
#     """
#     执行完目前所有的任务，线程池批量执行
#     """
#     # 1 检查是否有有效任务，没有则退出
#     start_time = datetime.now()
#     remaining_count = 0
#     if remaining_count == 0:
#         return
#     task_done_num = 0
#
#     # 3 线程池执行io任务
#     workers = 3
#     task_num = workers * 2  # 每次最多获取的任务数
#     with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
#         # 获取初始任务, 最多取(workers * 2)个，且不超过剩余任务数量
#         fetch_size = min(task_num, remaining_count)
#         # fetch_tasks = get_page(per_page=fetch_size)
#         fetch_tasks = []
#         # 待处理文件名称，防止重复添加
#         task_todo = set()
#         for record in fetch_tasks:
#             task_todo.add(record.name)
#         if len(fetch_tasks) > 0:
#             logging.info(f"得到{len(fetch_tasks)}个任务")
#         # 提交初始任务
#         futures = {}
#         while task_todo:
#             name = task_todo.pop()
#             future = executor.submit(test_worker, name)
#             futures[future] = name
#
#         with tqdm(
#                 total=len(futures),
#                 desc="srt_task 任务",
#                 colour="green",
#                 dynamic_ncols=True,
#                 bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} {elapsed}\n",
#         ) as bar:
#             # 处理已完成的任务并动态添加新任务
#             while get_remain_count() > 0 or futures:
#                 # 按完成的顺序遍历, 不按照futures提交的顺序遍历
#                 for future in as_completed(futures):
#                     name = futures[future]
#                     future.result()  # 实际每次阻塞发生的位置
#                     # 从字典中移除已完成的任务
#                     del futures[future]
#                     task_done_num += 1
#                     # 进度条+1
#                     bar.update(1)
#                     # 进度条到达100%，后续total显示不正常，需要手动重置
#                     if bar.n >= bar.total:
#                         bar.disable = True
#                         bar.reset(total=task_done_num + len(futures))  # 重置总进度
#                         bar.n = task_done_num  # 设置当前进度
#                         bar.disable = False  # 重新启用
#                         bar.refresh()  # 刷新显示
#
#                     # 如果有待添加的任务，添加新任务
#                     if len(futures) < task_num:
#                         # 获取补充任务, 最多取(workers * 2)个，且不超过剩余任务数量
#                         remaining_count = videofiles.get_zh_task_count()
#                         fetch_size = min(task_num, remaining_count)
#                         fetch_tasks = videofiles.get_zh_task_page(per_page=fetch_size)
#                         # 待处理文件名称，防止重复添加
#                         task_todo = set()
#                         for VideoFile_record in fetch_tasks:
#                             task_todo.add(VideoFile_record.name)
#                         if len(fetch_tasks) > 0:
#                             logging.info(f"得到{len(fetch_tasks)}个任务")
#                         while task_todo:
#                             name = task_todo.pop()
#                             future = executor.submit(srt_worker, client, name)
#                             futures[future] = name
#
#                     # 处理完一个任务后立即继续循环
#                     break
#
#     # 4 结束,输出统计信息
#     end_time = datetime.now()
#     time_diff = end_time - start_time
#     logging.info(
#         f"完成{task_done_num}个任务,耗时 {time_tool.format_timedelta(time_diff)}"
#     )
